package com.mes.web.controller.lc;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.mes.entity.lc.MaterialStock;
import com.mes.entity.lc.ProductStock;
import com.mes.entity.lc.Stockfy;
import com.mes.entity.tdd.tj.Tpage;
import com.mes.service.lc.MaterialStockService;
import com.mes.service.lc.ProductStockService;
import com.mes.utils.ExcelUtils;
import com.mes.utils.ResponseUtil;
import com.mes.utils.StringUtil;

/**
 * 库存管理Controller
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/lcstock")
public class StockController {
	
	@Autowired
	MaterialStockService   materialStockService; //物料
	@Autowired
	ProductStockService	   productStockService;  //产品
	
	/**
	 * 库存查询
	 * @param stockfy
	 * @param response
	 * @param limit
	 * @param offset
	 * @throws Exception
	 */
	@RequestMapping("/selectfycx")
	public @ResponseBody void selectfycx(
			Stockfy stockfy,HttpServletResponse response,
			@RequestParam(value = "limit", required = false) String limit,
			@RequestParam(value = "offset", required = false) String offset)
			throws Exception {
		
		stockfy.setPage(Integer.parseInt(offset) / Integer.parseInt(limit));
		
		// 每页条数
		stockfy.setPageSize(Integer.parseInt(limit));

		if (StringUtil.isEmpty(stockfy.getName())) {
			stockfy.setName(null);
		}
		if (StringUtil.isEmpty(stockfy.getSsck())) {
			stockfy.setSsck(null);
		}
		if (StringUtil.isEmpty(stockfy.getCar())) {
			stockfy.setCar(null);
		}
		if (StringUtil.isEmpty(stockfy.getIscw())) {
			stockfy.setIscw(null);
		}

		System.err.println(stockfy.getIscw() + "------------状态");
		//根据状态进行不同的分页查询  ，1 为物料查询，2 为产品查询
		if("2".equals(stockfy.getIscw())){
			
			// 物料
			List<MaterialStock> materlist = materialStockService.selectfycx(stockfy);
			int a = materialStockService.selectfycxcont(stockfy);
			JsonConfig config = new JsonConfig();
			JSONObject jsonObject = new JSONObject();
			JSONArray jsonArray = JSONArray.fromObject(materlist, config);
			jsonObject.put("rows", jsonArray);
			jsonObject.put("total", a);
			ResponseUtil.write(response, jsonObject);
			
		}else if ("1".equals(stockfy.getIscw())){
			
			// 产品
			List<ProductStock> produlist = productStockService.selectfycx(stockfy);
			int a = productStockService.selectfycxcont(stockfy);
			JsonConfig config = new JsonConfig();
			JSONObject jsonObject = new JSONObject();
			JSONArray jsonArray = JSONArray.fromObject(produlist, config);
			jsonObject.put("rows", jsonArray);
			jsonObject.put("total", a);
			ResponseUtil.write(response, jsonObject);			
			
		}
		
	}

	
	/**
	 * 库存报表查询
	 * @throws Exception 
	 */
	@RequestMapping("/selectBB")
	public void selectBB(String type, HttpServletResponse response, HttpServletRequest request) throws Exception{
		
		//1产品  2物料
		
		if("1".equals(type)){
			
			List<ProductStock> produlist = productStockService.selectProductStock();
			JSONObject json = new JSONObject();
			json.put("data", produlist);
			ResponseUtil.write(response, json);
			
		}else if("2".equals(type)){
			
			List<MaterialStock> material = materialStockService.selectMaterialStock();
			JSONObject json = new JSONObject();
			json.put("data", material);
			ResponseUtil.write(response, json);
		}
	}

	/**
	 * 导出当前页数据
	 * @param pageBean
	 * @param limit
	 * @param offset
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/doExportP")
	public void doExport(
			Stockfy stockfy,HttpServletResponse response,
			@RequestParam(value = "limit", required = false) String limit,
			@RequestParam(value = "offset", required = false) String offset)
			throws Exception {
		
		stockfy.setPage(Integer.parseInt(offset) / Integer.parseInt(limit));
		
		// 每页条数
		stockfy.setPageSize(Integer.parseInt(limit));

		if (StringUtil.isEmpty(stockfy.getName())) {
			stockfy.setName(null);
		}
		if (StringUtil.isEmpty(stockfy.getSsck())) {
			stockfy.setSsck(null);
		}
		if (StringUtil.isEmpty(stockfy.getCar())) {
			stockfy.setCar(null);
		}
		if (StringUtil.isEmpty(stockfy.getIscw())) {
			stockfy.setIscw(null);
		}
		// 产品
		List<ProductStock> produlist = productStockService.selectfycx(stockfy);
		List<List<String>> lists = productzhuanlist(produlist);
		ExcelUtils.export("产品库存当前数据",namess(), response,lists );
	}	
	/**
	 * 导出所有数据
	 * @param pageBean
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/doExportallP")
	public void doExportall(Tpage pageBean,HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		Stockfy stockfy = new Stockfy();
		stockfy .setPage(0);
		// 每页条数
		stockfy.setPageSize(productStockService.selectfycxcont(stockfy));
		List<ProductStock> produlist = productStockService.selectfycx(stockfy);
		List<List<String>> lists = productzhuanlist(produlist);
		ExcelUtils.export("产品库存所有数据",namess(), response,lists);
	}	
	
	
	/**
	 * 导入
	 * @param file
	 * @param request
	 * @param response
	 * @throws URISyntaxException
	 * @throws IOException
	 */
	@RequestMapping("/uplodeFileP")
	public void importor(@RequestParam("pic") CommonsMultipartFile file,HttpServletRequest request, HttpServletResponse response) throws URISyntaxException, IOException{
		   String savePath = ((HttpSession) request).getServletContext().getRealPath("/WEB-INF/"+file.getOriginalFilename());
		   File newFile=new File(savePath);
		   //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
	       file.transferTo(newFile);
	       //取文件后缀
	       String subfix = savePath.lastIndexOf(".")==-1? "" : savePath.substring(savePath.lastIndexOf(".")+1);
	       System.out.println(subfix);
	       List<List<String>> lists = new ArrayList<>();
	       //获取导入行数
	       List<String> names = names();
	       int num = names.size();
	       if(subfix.equals("xls")){
	    	   lists = ExcelUtils.readXls(savePath, request,num);
	 	   }else if(subfix.equals("xlsx")){
	 		   lists = ExcelUtils.readXlsx(savePath, request,num);
	 	   }else{
	 	   		response.getWriter().print("0");
	 	   }
	       
	       /*HttpSession session  = request.getSession();
	        //从session中取出用户身份信息
	       Staff userSession = (Staff) session.getAttribute("staff");*/
	       String staffname = null;
	       SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
	       String   date   =   sDateFormat.format(new Date());
	       int count = 0;
	       int flag = 1; 
	       for (int i = 0; i < lists.size(); i++) {
	    	   List<String> list = new ArrayList<>();
	    	   list= lists.get(i);
	    	   
	    	   ProductStock stock = new ProductStock();
	    	   /** 所属仓库 */
	    	   stock.setSsck(list.get(0));
	    	   //品编——》id
	    	   String pnum = list.get(1);
	    	   if(null != pnum && !pnum.equals("")){
	    		   Long pid = productStockService.fingBynum(pnum);
	    		   if(null != pid && !pid.equals("")){
	    			   stock.setProductidd(pid);
	    		   }else{
	    			   continue;
	    		   }
	    	   }else{
	    		   continue;
	    	   }
	    	   /** 库存数量 */
	    	   stock.setNum(list.get(2));
	    	   //批号
	    	   stock.setRemark1(list.get(3));
	    	   //条形码
	    	   stock.setRemark2(list.get(4));
	    	   
	    	   int ff = addstockP(stock, request, date, staffname);
	    	   stock = null;
	    	   if (ff == 0) {
	    		   flag = 0;
	    		   break;
	    	   }
	    	   count ++;
	       }
	       if(count == 0){
	    	   flag = -1;
	       }
	       response.getWriter().print(flag);
	 }
	/**
	 * 导出模板的表头
	 * @return
	 */
	public List<String> names(){
		List<String> list = new ArrayList<>();
		list.add("所属仓库");
		list.add("品编");
		list.add("库存数量");
		list.add("批次");
		list.add("条形码");
		return list;
	}
	
	/**
	 * 导出数据表头
	 * @return
	 */
	public List<String> namess(){
		List<String> list = new ArrayList<>();
		list.add("所属仓库");
		list.add("车种");
		list.add("品名");
		list.add("品编");
		list.add("颜色");
		list.add("初期库存");
		list.add("本月入库");
		list.add("本月出库");
		list.add("库存数量");
		list.add("最低安全库存量");
		return list;
	}
	/**
	 * 根据导出数据表头把List<Staff>转List<List<String>>
	 * @param produlist
	 * @return
	 */
	public List<List<String>> productzhuanlist (List<ProductStock> produlist){
		List<List<String>> lists = new ArrayList<>();
		for (ProductStock stock : produlist) {
			List<String> list = new ArrayList<>();
			list.add(stock.getSsck());
			
			if (null != stock.getProduct()) {
				list.add(stock.getProduct().getCartype());
				list.add(stock.getProduct().getName());
				list.add(stock.getProduct().getNum());
				list.add(stock.getProduct().getColor());
			}else{
				list.add(null);
				list.add(null);
				list.add(null);
				list.add(null);
			}
			list.add(stock.getBeginnum());
			list.add(stock.getMonthcome());
			list.add(stock.getMonthgo());
			list.add(stock.getNum());
			if (null != stock.getProduct()) {
				list.add(stock.getProduct().getRemark5());
			}else{
				list.add(null);
			}
			
			lists.add(list);
			list = null;
		}
		return lists;
	}
	/**
	 * 导入数据是的添加方法（如果不满足添加条件，直接过滤）
	 * @param stock
	 * @param request
	 * @param date
	 * @param staffname
	 * @return
	 */
	public int addstockP(ProductStock stock,
			HttpServletRequest request,String date,String staffname){
		int flag = 0;
        
    	//添加库区
    	//录入人
		stock.setPeop(staffname);
    	//录入时间
    	stock.setLrtime(date);
    	//添加
    	Long id = productStockService.add(stock);
    	//添加成功
    	if (null != id && id >= 1) {
    		flag = 1;
    		//未成功
    	} else {
    		flag = 0;
    	}
		return flag;
	}
}
